<script setup>
import { onMounted, ref, onUnmounted, watch } from "vue";
import {
  salesBondPage,
  salesBondInfo,
  createOrder,
  createQrCodeWx,
  createQrCodeAlipay,
  queryPayResult,
  bondRefund,
} from "@/api/bond";
import CommonModal from "@/components/modal/CommonModal.vue";
import { ElMessage } from "element-plus";
import QrcodeVue from "qrcode.vue";

onMounted(() => {
  getInfo();
  getList();
});

// 保证金充值退款记录列表
const list = ref([]);
const getList = async () => {
  try {
    const res = await salesBondPage({
      pageNum: 1,
      pageSize: 200,
    });
    console.log(res);
    list.value = res.data.records;
  } catch (err) {
    console.log(err);
  }
};
// 保证金主数据
const info = ref({});
const getInfo = async () => {
  try {
    const res = await salesBondInfo();
    console.log(res);
    info.value = res.data;
  } catch (err) {
    console.log(err);
  }
};

const payAmount = ref(0);
const payModelShow = ref(false);
// 创建保证金充值订单
const createLoading = ref(false);
const orderInfo = ref(null);
const createBondOrder = async () => {
  if (!info.value || !info.value.needBound) {
    ElMessage.warning("未获取到待缴纳保证金数据，请重试");
    return;
  }
  if (info.value.boundAmount >= info.value.needBound) {
    ElMessage.warning("您的保证金已缴清");
    return;
  }
  createLoading.value = true;
  try {
    payAmount.value = info.value.needBound - (info.value.boundAmount || 0);
    const amount = info.value.needBound - (info.value.boundAmount || 0);
    if (amount <= 0) {
      ElMessage.warning("保证金已缴清");
      return;
    }
    const res = await createOrder({
      amount,
    });
    console.log(res);
    orderInfo.value = res.data;
    await getQrCode();
  } catch (err) {
    console.log(err);
  } finally {
    createLoading.value = false;
  }
};
// 获取微信支付二维码
const qrcode = ref(null);
const qrcodeLoading = ref(false);
const expireTimeStr = ref("");
const expireTime = ref("");
const expireTimer = ref(null);
const getQrCode = async () => {
  if (!orderInfo.value) {
    ElMessage.warning("未获取到待缴纳保证金数据，请重试");
    return;
  }
  qrcodeLoading.value = true;
  try {
    qrcode.value = null;
    expireTimeStr.value = "";
    expireTime.value = "";
    const res = await createQrCodeWx({
      id: orderInfo.value.id,
    });
    if (!res.data || !res.data.url) {
      ElMessage.warning("获取微信支付二维码失败，请重试");
      return;
    }
    qrcode.value = res.data.url;
    expireTimeStr.value = expireTimeHandle(res.data.expireTime);
    expireTime.value = res.data.expireTime;
    payModelShow.value = true;
    if (queryTimer.value) {
      clearInterval(queryTimer.value);
      queryTimer.value = null;
    }
    queryTimer.value = setInterval(() => {
      queryPayResultHandle();
    }, 3000);
    if (expireTimer.value) {
      clearInterval(expireTimer.value);
      expireTimer.value = null;
    }
    expireTimer.value = setInterval(() => {
      expireTimeStr.value = expireTimeHandle(res.data.expireTime);
    }, 1000);
  } catch (err) {
    console.log(err);
  } finally {
    qrcodeLoading.value = false;
  }
};
// 获取支付宝支付二维码
const getQrCodeAlipay = async () => {
  if (!orderInfo.value) {
    ElMessage.warning("未获取到待缴纳保证金数据，请重试");
    return;
  }
  qrcodeLoading.value = true;
  try {
    qrcode.value = null;
    expireTimeStr.value = ref("");
    expireTime.value = "";
    const res = await createQrCodeAlipay({
      id: orderInfo.value.id,
    });
    if (!res.data || !res.data.url) {
      ElMessage.warning("获取支付宝支付二维码失败，请重试");
      return;
    }
    qrcode.value = res.data.url;
    expireTimeStr.value = expireTimeHandle(res.data.expireTime);
    expireTime.value = res.data.expireTime;
    payModelShow.value = true;
    if (queryTimer.value) {
      clearInterval(queryTimer.value);
      queryTimer.value = null;
    }
    queryTimer.value = setInterval(() => {
      queryPayResultHandle();
    }, 3000);
    if (expireTimer.value) {
      clearInterval(expireTimer.value);
      expireTimer.value = null;
    }
    expireTimer.value = setInterval(() => {
      expireTimeStr.value = expireTimeHandle(res.data.expireTime);
    }, 1000);
  } catch (err) {
    console.log(err);
  } finally {
    qrcodeLoading.value = false;
  }
};
// 切换支付方式
const payType = ref("wx");
const changePayType = () => {
  payType.value = payType.value === "wx" ? "alipay" : "wx";
  if (payType.value === "wx") {
    getQrCode();
  } else {
    getQrCodeAlipay();
  }
};
// 刷新
const roloadQrcode = () => {
  if (payType.value === "wx") {
    getQrCode();
  } else {
    getQrCodeAlipay();
  }
};

// 过期时间计算，返回4分44秒格式
const expireTimeHandle = (expireTime) => {
  // 1. 解析传入的时间字符串（格式："2025-04-04 00:29:09"）
  const expireDate = new Date(expireTime);

  // 2. 获取当前时间
  const now = new Date();

  // 3. 计算剩余时间（毫秒）
  const remainingTime = expireDate - now;

  // 4. 如果已过期或无效时间
  if (remainingTime <= 0 || isNaN(remainingTime)) {
    return "已过期";
  }

  // 5. 计算分钟和秒数
  const minutes = Math.floor(remainingTime / (1000 * 60));
  const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

  // 6. 返回格式化的字符串（如 "4分44秒"）
  return `${minutes}分${seconds}秒`;
};

// 查询支付结果
const queryTimer = ref(null);
const queryPayResultHandle = async () => {
  try {
    const res = await queryPayResult({
      id: orderInfo.value.id,
    });
    if (res.data && res.data.status === 1) {
      ElMessage.success("保证金支付成功");
      payModelShow.value = false;
      getInfo();
      getList();
    } else {
      //ElMessage.warning("保证金支付失败");
    }
  } catch (err) {
    console.log(err);
  }
};

onUnmounted(() => {
  if (queryTimer.value) {
    clearInterval(queryTimer.value);
  }
});

watch(payModelShow, (val) => {
  if (!val) {
    if (expireTimer.value) {
      clearInterval(expireTimer.value);
      expireTimer.value = null;
    }
    if (queryTimer.value) {
      clearInterval(queryTimer.value);
    }
  }
});

// 保证金退款
const refundModelShow = ref(false);
const refundReason = ref("");
const refund = async () => {
  try {
    const res = await bondRefund({
      amount: info.value.boundAmount,
      reason: refundReason.value,
    });
    console.log(res);
    if (res.code === 200) {
      ElMessage.success("退款申请提交成功，等待审核。");
      refundModelShow.value = false;
      getInfo();
      getList();
    }
  } catch (err) {
    console.log(err);
  }
};
// 退款金额输入
const refundAmountInput = (val) => {
  const inputVal = val.target.value;
  if (inputVal > info.value.boundAmount) {
    ElMessage.warning("退款金额不能大于当前可退保证金");
    refundAmount.value = Number(info.value.boundAmount);
  }
};
</script>

<template>
  <div class="bond-box">
    <div class="should">
      <p class="title">
        <span>应缴保证金</span>
        <span
          >保证金是保障平台好卖家和平台合理权益的必要手段，请务必按时缴纳，逾期15日后将会被吊销开店资格。</span
        >
      </p>
      <div class="info">
        <h3>¥ {{ info.needBound || 0 }}</h3>
        <div class="have">
          <p>
            <span>有无违规</span>
            <span>{{ info.violation === 0 ? "无违规" : "有违规" }}</span>
          </p>
          <p>
            <span>咨询数</span> <span>{{ info.consultCount }}</span>
          </p>
          <p>
            <span>咨询转化率</span> <span>{{ info.coverRate }}%</span>
          </p>
          <p>
            <span>平均转化率</span> <span>{{ info.averageRate }}%</span>
          </p>
        </div>
      </div>
    </div>
    <div class="reality">
      <p class="title"><span>实缴保证金</span></p>
      <div class="info">
        <h3>¥ {{ info.boundAmount }}</h3>
        <div class="btn">
          <el-button class="recharge" @click="createBondOrder" :loading="createLoading"
            >充值并缴纳</el-button
          >
          <el-button
            class="refund"
            v-if="info.boundAmount && info.boundAmount > 0"
            @click="refundModelShow = true"
            >退款</el-button
          >
        </div>
      </div>
    </div>
  </div>
  <div class="detailed">
    <p class="title">保证金明细</p>
    <div class="item" v-for="item in list" :key="item.id">
      <div class="left-title">
        <p>
          {{ item.bondTitle }}
          <span
            :class="{ 'status-1': item.status === 0, 'status-2': item.status === 2 }"
            >{{ item.status === 0 ? "待审核" : item.status === 2 ? "退款中" : "" }}</span
          >
        </p>
        <p>{{ item.createTime }}</p>
      </div>
      <div class="amount">
        <p :class="{ add: item.type != 1 }">
          {{ item.type === 1 ? "+" : "-" }} {{ item.amount }}
        </p>
        <p v-if="item.type === 2">退款原因：{{ item.refundReason }}</p>
      </div>
    </div>
    <el-empty v-if="list.length === 0" description="暂无数据" />
  </div>
  <!-- 充值弹窗 -->
  <CommonModal
    v-if="payModelShow"
    title="保证金充值"
    :width="400"
    :showCancel="false"
    :showConfirm="false"
    @close="payModelShow = false"
  >
    <template #content>
      <div class="bond-modal">
        <h5 class="title">充值金额</h5>
        <div class="amount-input">
          <input class="amount-input-input" type="text" :value="payAmount" disabled />
          <button class="amount-input-button">充值</button>
        </div>
        <h4 class="pay-type-title">
          请使用{{ payType === "wx" ? "微信" : "支付宝" }}扫码支付
        </h4>
        <div class="pay-qrcode">
          <div v-if="payType === 'wx'" class="qrcode-img" v-loading="qrcodeLoading">
            <qrcode-vue :value="qrcode" :size="149"></qrcode-vue>
          </div>
          <iframe
            v-loading="qrcodeLoading"
            v-if="payType === 'alipay'"
            element-loading-text="加载中"
            :srcdoc="qrcode"
            frameborder="0"
            marginwidth="0"
            marginheight="0"
            scrolling="no"
            width="152"
            height="152"
            style="width: 152px; height: 152px"
          >
          </iframe>
          <div class="load-err" v-if="!qrcodeLoading && !qrcode">
            <img src="@/assets/cs-qrcode-img.png" style="opacity: 0.5" />
            <span class="qrcode-error">
              <b>{{ expireTimeStr === "已过期" ? "已过期" : "加载失败！" }}</b>
            </span>
          </div>
        </div>
        <p class="code-expire-time">
          距离二维码过期还剩 <span>{{ expireTimeStr }}</span>
        </p>
        <p class="reload" @click="roloadQrcode" v-if="expireTimeStr == '已过期'">
          <img src="@/assets/reload-icon.png" />
          <span>刷新</span>
        </p>
        <p class="change-pay-type">
          切换使用
          <span @click="changePayType">{{ payType === "wx" ? "支付宝" : "微信" }}</span>
          支付
        </p>
      </div>
    </template>
  </CommonModal>
  <!-- 保证金退款 -->
  <CommonModal
    v-if="refundModelShow"
    title="退款"
    :width="400"
    @close="refundModelShow = false"
    @confirm="refund"
  >
    <template #content>
      <div class="bond-modal">
        <h5 class="title refund-title">
          退款金额
          <span class="amount-info"
            >当前可退保证金：<span>¥{{ info.needBound || 0 }}</span></span
          >
        </h5>
        <div class="amount-input">
          <input
            class="amount-input-input"
            type="number"
            :value="info.boundAmount"
            placeholder="请输入退款金额"
            @input="refundAmountInput"
            disabled
          />
        </div>
        <div class="refund-reason">
          <h5 class="title">退款原因</h5>
          <textarea
            class="refund-reason-textarea"
            v-model="refundReason"
            placeholder="请输入退款原因"
          ></textarea>
        </div>
      </div>
    </template>
  </CommonModal>
</template>

<style scoped lang="scss">
.bond-box {
  display: flex;
}
.should,
.reality {
  flex: 1;
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  padding: 20px;
  .title {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    span:nth-child(1) {
      font-size: 16px;
      color: #191e28;
      font-weight: bold;
    }
    span:nth-child(2) {
      font-size: 12px;
      color: rgba(25, 30, 40, 0.48);
    }
  }
  .info {
    background: rgba(25, 30, 40, 0.02);
    border-radius: 12px 12px 12px 12px;
    padding: 16px;
    h3 {
      text-align: center;
      font-size: 20px;
      color: #1dbf73;
      margin-bottom: 14px;
    }
    .have {
      display: flex;
      align-items: center;
      justify-content: space-between;
      p {
        flex: 1;
        display: flex;
        flex-direction: column;
        text-align: center;
        span:nth-child(1) {
          color: rgba(25, 30, 40, 0.6);
          margin-bottom: 6px;
        }
        span:nth-child(2) {
          color: #191e28;
          font-weight: bold;
        }
      }
    }
  }
}
.reality {
  margin-left: 16px;
  .btn {
    display: flex;
    align-items: center;
    justify-content: center;
    button {
      border: none;
      cursor: pointer;
    }
    .recharge {
      width: 160px;
      height: 44px;
      background: #1dbf73;
      border-radius: 8px 8px 8px 8px;
      font-size: 16px;
      color: #ffffff;
      margin-right: 16px;
    }
    .refund {
      width: 160px;
      height: 44px;
      background: #ffffff;
      border-radius: 8px 8px 8px 8px;
      border: 1px solid rgba(25, 30, 40, 0.08);
    }
  }
}
.detailed {
  background: #ffffff;
  box-shadow: 0px 0px 16px 0px rgba(11, 13, 18, 0.06);
  border-radius: 16px 16px 16px 16px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  padding: 20px;
  margin-top: 16px;
  .title {
    font-size: 16px;
    color: #191e28;
    font-weight: 600;
    padding-bottom: 10px;
    border-bottom: 1px solid #ededee;
  }
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px 0;
    border-bottom: 1px solid #ededee;
    &:last-child {
      border-bottom: none;
    }
    .left-title {
      p {
        .status-1 {
          padding: 3px 8px;
          background: rgba(29, 191, 115, 0.08);
          border-radius: 14px;
          color: #1dbf73;
          font-size: 14px;
          margin-left: 10px;
        }
        .status-2 {
          padding: 3px 8px;
          background: rgba(255, 140, 29, 0.08);
          border-radius: 14px;
          color: #ff8c1d;
          font-size: 14px;
          margin-left: 10px;
        }
      }
      p:nth-child(1) {
        font-weight: 600;
        font-size: 20px;
        color: #191e28;
        margin-bottom: 8px;
        display: flex;
        align-items: center;
      }
      p:nth-child(2) {
        color: rgba(25, 30, 40, 0.72);
      }
    }
    .amount {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      p:nth-child(1) {
        font-size: 24px;
        color: #191e28;
        font-weight: bold;
      }
      p.add {
        color: #ff4f4f;
      }
      p:nth-child(2) {
        font-size: 14px;
        color: rgba(25, 30, 40, 0.48);
      }
    }
  }
}
.bond-modal {
  display: flex;
  flex-direction: column;
  .title {
    font-size: 14px;
    color: #191e28;
    line-height: 36px;
    user-select: none;
  }
  .amount-input {
    display: flex;
    align-items: center;
    gap: 12px;
    .amount-input-input {
      flex: 1;
      border: 1px solid rgba(25, 30, 40, 0.08);
      border-radius: 6px 6px 6px 6px;
      height: 40px;
      padding: 0 12px;
      box-sizing: border-box;
    }
    .amount-input-button {
      flex: 0 0 92px;
      height: 40px;
      background: #1dbf73;
      border-radius: 6px 6px 6px 6px;
      color: #ffffff;
      font-size: 14px;
      border: none;
    }
  }
  .pay-type-title {
    font-size: 20px;
    font-weight: bold;
    color: #191e28;
    line-height: 24px;
    text-align: center;
    margin: 24px 0 16px 0;
    user-select: none;
  }
  .change-pay-type {
    text-align: center;
    margin-bottom: 16px;
    user-select: none;
    span {
      color: #1dbf73;
      cursor: pointer;
    }
  }
  .pay-qrcode {
    width: 172px;
    height: 172px;
    border-radius: 12px;
    background: #fff;
    border: 1px solid rgba(25, 30, 40, 0.08);
    overflow: hidden;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .qrcode-img {
      width: 172px;
      height: 172px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .qrcode-error {
      color: #999;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      top: 0;
      left: 0;
      background: rgba(255, 255, 255, 0.8);
      z-index: 2;
    }
    .load-err {
      position: absolute;
      width: 172px;
      height: 172px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .code-expire-time {
    color: rgba(25, 30, 40, 0.6);
    font-size: 14px;
    margin-top: 12px;
    margin-bottom: 10px;
    text-align: center;
    user-select: none;
    span {
      color: #ff4f4f;
    }
  }
  .reload {
    flex: 0 0 100%;
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    text-align: center;
    margin-bottom: 10px;
    cursor: pointer;
    img {
      width: 16px;
      height: 16px;
      margin-right: 2px;
    }
    span {
      font-size: 12px;
      color: #1dbf73;
    }
  }
}
.refund-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .amount-info {
    font-size: 12px;
    color: rgba(25, 30, 40, 0.6);
    span {
      font-size: 12px;
      color: #1dbf73;
      font-weight: bold;
    }
  }
}
.refund-reason {
  margin-top: 10px;
  .refund-reason-textarea {
    width: 100%;
    height: 100px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    border-radius: 6px 6px 6px 6px;
    padding: 10px;
    box-sizing: border-box;
  }
}
</style>
